import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {PagesService} from "../pages.service";
import {Setting} from "../../../public/setting/setting";
import {Router} from "@angular/router";
import {SettingUrl} from "../../../public/setting/setting_url";
import {StaffStates} from "../../../public/setting/enums";
import {NzNotificationService} from "ng-zorro-antd";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public validateForm: FormGroup;//登录的表单
  public app = Setting.APP; //平台信息
  @ViewChild('jobnumber') jobnumberEl: ElementRef;

  constructor(public fb: FormBuilder, private pagesService: PagesService, public router: Router,
              private notification: NzNotificationService,) {
    this.validateForm = this.fb.group({
      jobnumber: [null, [Validators.required]],
    });
    let staffInfo = sessionStorage.getItem(Setting.storage.staffInfo);
    if (staffInfo) this.router.navigate([SettingUrl.ROUTERLINK.basic.home], {replaceUrl: true});//如果有token，跳转到首页
  }

  ngOnInit() {
    let me = this;
    setTimeout(function () {
      me.jobnumberEl.nativeElement.focus();//弹窗出现时，输入框自动获取焦点
    })
  }

  /**
   * 获取扫描的箱SN码
   * @param e
   */
  getJobnumber(e) {
    if (e.keyCode == 13 || e.keyCode == 229) {
      if (e.value && e.value.trim() != '') {
        this.validateForm.patchValue({jobnumber: e.value})
      }
    }
  }

  /**
   * 扫描箱SN码输入框失焦时
   */
  onJobnumberBlur() {
    if (!this.validateForm.value.jobnumber) this.jobnumberEl.nativeElement.focus();
  }

  /**
   * 登录
   * @param $event
   * @param value
   */

  login = ($event) => {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    me.pagesService.login(me.validateForm.value.jobnumber).then((data: any) => {
      if (data && data.state === StaffStates.hire) {
        sessionStorage.setItem(Setting.storage.staffInfo, JSON.stringify(data));
        Setting.user = data;
        me.router.navigate([SettingUrl.ROUTERLINK.box.list]);//登陆成功
      } else if (data.state === StaffStates.leave) {
        this.notification.error('校验失败', '该员工已离职，不可登陆该系统')
      }
    });
  };


  /**
   * from表单
   * @param name
   * @returns {AbstractControl}
   */
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
